package com.telit.android.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import com.telit.android.constant.StatusAndTypeConstant;
import com.telit.android.dto.*;
import com.telit.android.service.IAppTaskService;
import com.telit.android.service.ICommEventTaskTrackService;
import com.telit.android.service.TrackService;
import com.telit.android.service.impl.UserInfoService;
import com.telit.common.annotation.Log;
import com.telit.common.constant.Constant;
import com.telit.common.constant.RoleCodeConstants;
import com.telit.common.core.utils.FeignUtils;
import com.telit.common.core.utils.Result;
import com.telit.common.dto.NormalTaskDTO;
import com.telit.common.dto.SimpleTrackDTO;
import com.telit.common.entity.AppTask;
import com.telit.common.entity.CommEventTaskTrack;
import com.telit.common.entity.DataReturn;
import com.telit.common.entity.PageData;
import com.telit.common.enums.*;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.RedisUtils;
import com.telit.common.util.TimeUtils;
import com.telit.firecommand.feign.RemoteFirecommandService;
import com.telit.firecommand.vo.ForesterVO;
import com.telit.upms.feign.RemoteUpmsService;
import com.telit.upms.vo.MicroSysUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * <p>
 * 任务表 前端控制器
 * </p>
 *
 * @author yummy
 * @since 2021-07-22
 */
@Api(tags = "01-任务相关接口", description = "/app-task")
@RestController
@RequestMapping("/app-task")
public class AppTaskController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private IAppTaskService appTaskService;

    @Autowired
    private ICommEventTaskTrackService commEventTaskTrackService;

    @Autowired
    private TrackService trackService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RemoteFirecommandService remoteFirecommandService;

    @Autowired
    private RemoteUpmsService remoteUpmsService;

    @PostMapping("/addHotportTrackTask")
    @ApiOperation("热点巡护任务下达")
    public DataReturn addHotportTrackTask(@RequestBody HotportTrackTaskDto hotportTrackTaskDto) throws Exception {
        Long value = appTaskService.addHotportTrackTask(hotportTrackTaskDto);
        return DataReturn.ok(value);
    }

    @PostMapping("/addHotportUavTask")
    @ApiOperation("热点巡航任务下达")
    public DataReturn addHotportUavTask(@RequestBody HotportUavTaskDto hotportUavTaskDto) throws Exception {
        Long value = appTaskService.addHotportUavTask(hotportUavTaskDto);
        return DataReturn.ok(value);
    }

    @Log(service = ServiceName.FIRE_ALARMS, businessType = BusinessType.BUSINESS_LOG, operatorType = OperatorType.WEB, businessOperatorType = BusinessOperatorType.RWXF)
    @ApiOperation(httpMethod = Constant.REQUEST_METHOD_POST,value = "任务下发")
    @PostMapping("/addOtherTask")
    public DataReturn addOtherTask(@RequestBody @Validated OtherTaskDto otherTaskDto) throws Exception {
        final TimeInterval timer = DateUtil.timer();
        AppTask appTask = otherTaskDto.getAppTask();
        //根据产品需求，截止时间默认任务下发时间后15min
        appTask.setEndTime(TimeUtils.getFiveMinAfter());
        Long value = appTaskService.addOtherTask(otherTaskDto);
        log.info("添加其他任务耗时:[{}]ms", timer.intervalRestart());
        //判断任务是否为空，任务不为空，类型也不为空
        if (otherTaskDto != null && otherTaskDto.getAppTask() != null) {
            String type = otherTaskDto.getAppTask().getType();
            if ("3".equals(type) || "9".equals(type)) {
                //火情核实任务处理记录
                IssueFireVerificationTask issueFireVerificationTask = new IssueFireVerificationTask();
                issueFireVerificationTask.setFireId(otherTaskDto.getEventId());
                //获取接收人数据集合
                Result<Map<Long, MicroSysUserVo>> selectByBatchIdsResult = remoteUpmsService.selectByBatchIds(
                        otherTaskDto.getRecieverIdList(), true);
                Map<Long, MicroSysUserVo> microSysUserVoMap = FeignUtils.unwrap(selectByBatchIdsResult);
                Collection<MicroSysUserVo> microSysUserVos = microSysUserVoMap.values();
                List<String> executePersonNameList = microSysUserVos.stream().map(MicroSysUserVo::getRealName).collect(
                        Collectors.toList());
                issueFireVerificationTask.setExecutePerson(executePersonNameList);
                log.info("执行循环遍历耗时:[{}]ms", timer.intervalRestart());
                remoteFirecommandService.addTaskDispose(issueFireVerificationTask);
                log.info("微服务内部调用耗时:[{}]ms", timer.intervalRestart());
            }
        }
        return DataReturn.ok(value);
    }
    /*@PostMapping("/addOtherTask")
    @ApiOperation("非热点巡护巡航任务下达")
    public DataReturn addOtherTask(@RequestBody @Validated OtherTaskDto otherTaskDto) throws Exception {
        Long value= appTaskService.addOtherTask(otherTaskDto);

        //记录火情任务下达信息
//        if ("1".equals(otherTaskDto.getEventType())) {

//            Long id = JwtTokenUtils.getId();
//            SysUserDetailVo userInfo = userInfoService.getUserInfo(id);
//            SysUserDetailVo userInfo = userInfoService.getUserInfo(1524651793085190146L);
//            List<Long> recieverIdList = otherTaskDto.getRecieverIdList();
//            List<ForesterDTO> foresterDTOList = new ArrayList<>();
            //调用upms服务次数过多
            *//*recieverIdList.forEach(e->{
                ForesterDTO foresterDTO = new ForesterDTO();
                SysUserDetailVo info = userInfoService.getUserInfo(e);
                BeanUtils.copyProperties(info,foresterDTO);
                foresterDTOList.add(foresterDTO);
            });*//*

//        }
        //判断任务是否为空，任务不为空，类型也不为空
        if(otherTaskDto !=null && otherTaskDto.getAppTask()!=null){
            String type = otherTaskDto.getAppTask().getType();
            if("3".equals(type) || "9".equals(type)){
                //火情核实任务处理记录
                IssueFireVerificationTask issueFireVerificationTask = new IssueFireVerificationTask();
                issueFireVerificationTask.setFireId(otherTaskDto.getEventId());
                //获取接收人数据集合
                List<SysUserDetailVo> sysUserDetailVoList=userInfoService.queryUserInfoByIds(otherTaskDto.getRecieverIdList());
                List<String> executePersonNameList=new ArrayList<>();
                if(sysUserDetailVoList !=null && sysUserDetailVoList.size()>0){
                    sysUserDetailVoList.forEach(sysUserDetailVo -> {
                        if(StringUtil.isNotEmpty(sysUserDetailVo.getRealName())){
                            executePersonNameList.add(sysUserDetailVo.getRealName());
                        }
                    });
                }
                issueFireVerificationTask.setExecutePerson(executePersonNameList);
                *//*PushFireMsg pushFireMsg = new PushFireMsg();
                List<Long> recieverIdList = otherTaskDto.getRecieverIdList();
                List<ForesterDTO> foresterDTOList = new ArrayList<>();
                //更换成通过id集合获取用户信息接口
                List<SysUserDetailVo> sysUserDetailVoList=userInfoService.queryUserInfoByIds(recieverIdList);
                if(sysUserDetailVoList !=null && sysUserDetailVoList.size()>0){
                    sysUserDetailVoList.forEach(sysUserDetailVo -> {
                        ForesterDTO foresterDTO = new ForesterDTO();
                        BeanUtils.copyProperties(sysUserDetailVo,foresterDTO);
                        foresterDTOList.add(foresterDTO);
                    });
                }
                //处置记录
                pushFireMsg.setForesterDTOList(foresterDTOList);
                pushFireMsg.setFireId(otherTaskDto.getEventId());*//*
                fireCommandFeignClient.addTaskDispose(issueFireVerificationTask);
            }
        }
        return DataReturn.ok(value);
    }*/

//    @PostMapping("/startExecuteTask")
//    @ApiOperation("开始执行任务")
//    public DataReturn startExecuteTask(@RequestParam(required = true) Long subTaskId,HttpServletRequest httpServletRequest){
//        appTaskService.startExecuteTask(subTaskId,httpServletRequest);
//        return DataReturn.ok();
//    }
//
//    @PostMapping("/finishExecuteTask")
//    @ApiOperation("完成任务")
//    public DataReturn finishExecuteTask(@RequestParam(required = true) Long subTaskId,HttpServletRequest httpServletRequest){
//        appTaskService.finishExecuteTask(subTaskId,httpServletRequest);
//        return DataReturn.ok();
//    }

    @PostMapping("/executeTask")
    @ApiOperation("执行任务")
    public DataReturn executeTask(@Validated @RequestBody ExecuteTaskDto executeTaskDto) {
        executeTaskDto.setStatus("2");// 2是执行中
        appTaskService.executeTask(executeTaskDto);
        return DataReturn.ok();
    }

    @PostMapping("/finishTask")
    @ApiOperation("完成任务")
    public DataReturn finishTask(@Validated @RequestBody FinishTaskDto finishTaskDto) {
        RedisUtils.removeBoundHash(String.valueOf(finishTaskDto.getTaskId()), String.valueOf(finishTaskDto.getForestkeeperId()));
        finishTaskDto.setStatus("3");// 完成任务
        // 当是日常任务类型结束
        if ("1".equals(finishTaskDto.getTrackType()) || "7".equals(finishTaskDto.getTrackType())) {
            appTaskService.normalTaskFinishTask(finishTaskDto);
            return DataReturn.ok();
        }
        appTaskService.finishTask(finishTaskDto);
        return DataReturn.ok();
    }

    @GetMapping("/delete/{id}")
    @ApiImplicitParam(name = "id", value = "配置ID", paramType = "path", dataType = "Integer")
    public DataReturn delete(@PathVariable("id") Integer id) {
        int value = appTaskService.delete(id);
        return DataReturn.ok(value);
    }

    @GetMapping("/deleteBatch")
    @ApiImplicitParam(name = "ids", value = "配置ID数组", paramType = "query", dataType = "integer[]")
    public DataReturn deleteBatch(Integer[] ids) {
        List<Integer> values = appTaskService.deleteBatch(ids);
        return DataReturn.ok(values);
    }

    @PostMapping("/update")
    @ApiOperation("修改")
    public DataReturn update(@RequestBody AppTask appTask) {
        appTaskService.updateData(appTask);
        return DataReturn.ok();
    }

/*    @PostMapping("/search")
    @ApiOperation("条件查询+分页")
    @ApiImplicitParams({@ApiImplicitParam(name="page",value="当前页面",dataType = "int",paramType = "query"),
    @ApiImplicitParam(name="rows",value = "每页记录数",dataType = "int",paramType = "query")})
    public DataReturn findListByPage(@RequestBody(required = false) AppTask appTask, Integer page,
                                     Integer rows){
        IPage<AppTask> appTaskPage = appTaskService.findListByPage(appTask,page, rows);
        Map<String,Object> retMap=new HashMap<String,Object>();
        retMap.put("appTask",appTaskPage.getRecords());
        retMap.put("total",appTaskPage.getTotal());
        return DataReturn.ok(retMap);
    }

    @PostMapping("/searchNoPage")
    @ApiOperation("条件查询")
    public DataReturn searchNoPage(@RequestBody(required = false) AppTask appTask){
        List<AppTask> appTaskList = appTaskService.searchNoPage(appTask);
        return DataReturn.ok(appTaskList);
    }*/

    @GetMapping("/findOne/{id}")
    @ApiOperation("根据id获取配置实体")
    @ApiImplicitParam(name = "id", value = "配置ID", paramType = "path", dataType = "Long")
    public DataReturn findById(@PathVariable Long id) {
        AppTask appTask = appTaskService.findById(id);
        return DataReturn.ok(appTask);
    }

    @GetMapping(value = "/findTasking", produces = "application/json;charset=UTF-8")
    @ApiOperation("查询正在任务中的护林员任务信息")
    public DataReturn findTaskingByUserId(@RequestParam("foresterIdList") List<Long> foresterIdList) {
        List<CommEventTaskTrack> list = commEventTaskTrackService.selectTaskingByUserId(foresterIdList, StatusAndTypeConstant.TASK_STATUS_ON);
        return DataReturn.ok(list);
    }

    @PostMapping(value = "/findTasking", produces = "application/json;charset=UTF-8")
    @ApiOperation("查询正在任务中的护林员任务信息-post方式,供远程调用,参数可能超过限制换成post")
    public DataReturn findTaskingByUserIdPost(@RequestBody List<Long> foresterIdList) {
        List<CommEventTaskTrack> list = commEventTaskTrackService.selectTaskingByUserId(foresterIdList, StatusAndTypeConstant.TASK_STATUS_ON);
        return DataReturn.ok(list);
    }

    @GetMapping(value = "/patrolList/{fireId}", produces = "application/json;charset=UTF-8")
    @ApiOperation("灾后管理-巡护巡航任务列表")
    public DataReturn patrolTaskByFireId(@PathVariable("fireId") Long fireId) {
        return DataReturn.ok(commEventTaskTrackService.patrolTaskByFireId(fireId));
    }

    @GetMapping("/searchTask")
    @ApiOperation("根据任务类型查询任务")
    @ApiImplicitParams({@ApiImplicitParam(name = "taskType", value = "任务类型1巡护任务 2 巡航任务", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页面", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "rows", value = "每页记录数", dataType = "int", paramType = "query")})
    public DataReturn searchTask(@RequestParam(required = true) Integer taskType, @RequestParam(required = true) Integer page,
                                 @RequestParam(required = true) Integer rows) {
        PageData<Object> appTaskPage = appTaskService.searchTask(taskType, page, rows);
        return DataReturn.ok(appTaskPage);
    }

    @GetMapping("/queryTotalTaskByCondition")
    @ApiOperation("根据条件查询总任务")
    public DataReturn queryTotalTaskByCondition(@RequestParam(required = true) Integer page,
                                                @RequestParam(required = true) Integer rows,
                                                @ModelAttribute AppTaskQueryDTO appTaskQueryDTO) {
        if (!StringUtils.hasText(appTaskQueryDTO.getTaskType())) {
            return DataReturn.failure(ResultCode.BAD_REQUEST, "taskType参数必填");
        }
        // 单个护林员参数有值的查询
        if (appTaskQueryDTO.getForestkeeperId() != null) {
            return DataReturn.ok(appTaskService.querySimplePersonTotalTaskByCondition(page, rows, appTaskQueryDTO));
        }

        List<Long> idList = new ArrayList<>();
        if (StrUtil.isNotEmpty(appTaskQueryDTO.getDistrictCode())) {
            //根据名称查询人员
            DataReturn<PageData<List<ForesterVO>>> qryUserListDataReturn = remoteFirecommandService.qryUserList(null,
                    null, appTaskQueryDTO.getDistrictCode(), true, RoleCodeConstants.ROLE_CODE_FORESTER, null, 1,
                    Integer.MAX_VALUE);
            if (!ResultCode.SUCCESS.getCode().equals(qryUserListDataReturn.getCode())) {
                throw new ForestBaseException(qryUserListDataReturn.getErrorMsg());
            }
            idList = qryUserListDataReturn.getData().getDatas().stream().map(
                    foresterVO -> Convert.toLong(foresterVO.getId())).collect(Collectors.toList());
            appTaskQueryDTO.setForestkeeperIdList(idList);
        }

        PageData<List<AppTask>> pageData = appTaskService.queryTotalTaskByCondition(page, rows, appTaskQueryDTO);
        // 获取待执行、执行中的任务总和
        List<String> statusList = new ArrayList<>();
        statusList.add("1");
        statusList.add("2");
        int unfinishedTaskCount = appTaskService.selectCountByTypeAndStatus1(appTaskQueryDTO.getTaskType(), statusList,
                idList);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("count", pageData.getCount());
        resultMap.put("current", pageData.getCurrent());
        resultMap.put("size", pageData.getSize());
        resultMap.put("datas", pageData.getDatas());
        resultMap.put("unfinishedTaskCount", unfinishedTaskCount); // 未完成的任务总数量(执行中,待执行状态)
        return DataReturn.ok(resultMap);
    }

    @GetMapping("/queryTaskDetailByTaskId")
    @ApiOperation("根据任务id查询明细")
    public DataReturn queryTaskDetailByTaskId(@RequestParam(required = true) Integer page,
                                              @RequestParam(required = true) Integer rows, @RequestParam(required = true) Long taskId) {
        PageData<Object> pageData = appTaskService.queryTaskDetailByTaskId(page, rows, taskId);
        return DataReturn.ok(pageData);
    }

    @GetMapping(value = "/cruiseTaskByUserId", produces = "application/json;charset=UTF-8")
    @ApiOperation("飞手信息-根据用户id查询正在任务中的巡航任务列表,多个任务状态用','分割;taskStatus=2(任务中)，1(待执行),3(已完成)")
    public DataReturn cruiseTaskByUserId(@Validated PatrolTaskQueryDTO patrolTaskQueryDTO) {
        return DataReturn.ok(appTaskService.listCruiseTaskByUserId(patrolTaskQueryDTO));
    }

    @GetMapping(value = "/cruiseTaskByUserIdPage", produces = "application/json;charset=UTF-8")
    @ApiOperation("飞手信息分页-根据用户id查询巡航任务列表分页,多个任务状态用','分割;taskStatus=2(任务中)，1(待执行),3(已完成)")
    public DataReturn cruiseTaskByUserIdPage(@RequestParam(defaultValue = "1") Integer current,
                                             @RequestParam(defaultValue = "10") Integer size,
                                             @Validated PatrolTaskQueryDTO patrolTaskQueryDTO) {
        return DataReturn.ok(appTaskService.listCruiseTaskByPage(current, size, patrolTaskQueryDTO));
    }

    @GetMapping(value = "/patrolTaskById", produces = "application/json;charset=UTF-8")
    @ApiOperation("护林员信息-根据用户id查询巡护任务列表,多个任务状态用','分割;taskStatus=2(任务中)，1(待执行),3(已完成)")
    public DataReturn<List<AppTrackDTO>> patrolTaskById(@Validated PatrolTaskQueryDTO patrolTaskQueryDTO) {
        return DataReturn.ok(appTaskService.listPatrolTaskByUserId(patrolTaskQueryDTO));
    }

    @GetMapping(value = "/patrolTaskByIdPage", produces = "application/json;charset=UTF-8")
    @ApiOperation("护林员信息分页-根据用户id查询巡护任务列表分页,多个任务状态用','分割;taskStatus=2(任务中)，1(待执行),3(已完成)")
    public DataReturn patrolTaskByIdPage(@RequestParam(defaultValue = "1") Integer current,
                                         @RequestParam(defaultValue = "10") Integer size,
                                         @Validated PatrolTaskQueryDTO patrolTaskQueryDTO) {
        return DataReturn.ok(appTaskService.listPatrolTaskByPage(current, size, patrolTaskQueryDTO));
    }

    @GetMapping(value = "/patrolTaskDetail/{id}/{forestkeeperId}", produces = "application/json;charset=UTF-8")
    @ApiOperation("护林员信息-查询护林员任务的详情")
    public DataReturn<AppTrackDTO> patrolTaskDetail(@PathVariable("forestkeeperId") Long forestkeeperId,
                                                    @PathVariable("id") Long id) {
        return DataReturn.ok(appTaskService.patrolDetailById(forestkeeperId, id));
    }

    /**
     * 根据无人机code查询执行任务
     *
     * @param uavCode
     * @return
     */
    @GetMapping("/queryTaskByUavCode")
    @ApiOperation("根据无人机code查询执行任务")
    public DataReturn queryTaskByUavCode(@RequestParam(required = false) String uavCode) {
        List<AppTask> data = appTaskService.queryTaskByUavCode(uavCode);
        return DataReturn.ok(data);
    }

    @GetMapping(value = "/cruiseTaskDetail/{id}/{forestkeeperId}", produces = "application/json;charset=UTF-8")
    @ApiOperation("飞手信息-查询飞手任务的详情")
    public DataReturn cruiseTaskDetail(@PathVariable("forestkeeperId") Long forestkeeperId, @PathVariable("id") Long id) {
        return DataReturn.ok(appTaskService.cruiseTaskDetailById(forestkeeperId, id));
    }

    @GetMapping(value = "/uavTaskByUavCode", produces = "application/json;charset=UTF-8")
    @ApiOperation("无人机信息-正在任务中的无人机任务列表")
    public DataReturn uavTaskByUavCode(@RequestParam("uavCode") String uavCode) {
        return DataReturn.ok(appTaskService.listUavTaskByUavCode(uavCode));
    }

    @PostMapping(value = "/startNormalTask", produces = "application/json;charset=UTF-8")
    @ApiOperation("开始日常巡护任务")
    public DataReturn startNormalTask(@Validated @RequestBody NormalTaskDTO normalTaskDTO) {
        return DataReturn.ok(appTaskService.startNormalTask(normalTaskDTO));
    }

    @GetMapping("/queryPatrolTaskNumByFireId")
    @ApiOperation("根据火情id查询任务数量")
    public DataReturn queryPatrolTaskNumByFireId(@RequestParam("fireId") Long fireId) {
        FireTaskNumberDTO data = appTaskService.queryPatrolTaskNumByFireId(fireId);
        return DataReturn.ok(data);
    }

    @GetMapping("/queryPatrolTaskByFireId")
    @ApiOperation("根据火情id查询任务列表（type 1 巡护任务 2 巡航任务）")
    public DataReturn queryPatrolTaskByFireId(@RequestParam("fireId") Long fireId, @RequestParam("status") String status, @RequestParam("type") Integer type, @RequestParam(required = true) Integer page,
                                              @RequestParam(required = true) Integer rows) {
        PageData<Object> pageData = appTaskService.queryPatrolTaskByFireId(fireId, status, type, page, rows);
        return DataReturn.ok(pageData);
    }

    @PostMapping(value = "/updateTrackId", produces = "application/json;charset=UTF-8")
    @ApiOperation("更新轨迹id")
    public DataReturn updateTrackId(@RequestBody SimpleTrackDTO simpleTrackDTO) {
        if (trackService.updateTrackId(simpleTrackDTO.getTaskId(), simpleTrackDTO.getForestkeeperId(), simpleTrackDTO.getTrackId()) <= 0) {
            return DataReturn.failure(ResultCode.OPERATE_ERROR, "更新轨迹id失败");
        }
        return DataReturn.ok();
    }

    @GetMapping(value = "/taskCount", produces = "application/json;charset=UTF-8")
    @ApiOperation("任务数量")
    public DataReturn taskCount(@RequestParam("taskType") String taskType, @RequestParam(required = false) Long userId,
                                @RequestParam("districtCode") String districtCode) {
        Map<String, Integer> resultMap = new HashMap<>();
        List<Long> idList = new ArrayList<>();
        if (StrUtil.isNotEmpty(districtCode)) {
            //根据名称查询人员
            DataReturn<PageData<List<ForesterVO>>> qryUserListDataReturn = remoteFirecommandService.qryUserList(null,
                    null, districtCode, true, RoleCodeConstants.ROLE_CODE_FORESTER, null, 1, Integer.MAX_VALUE);
            if (!ResultCode.SUCCESS.getCode().equals(qryUserListDataReturn.getCode())) {
                throw new ForestBaseException(qryUserListDataReturn.getErrorMsg());
            }
            idList = qryUserListDataReturn.getData().getDatas().stream().map(
                    foresterVO -> Convert.toLong(foresterVO.getId())).collect(Collectors.toList());

            // 待执行,执行中，已完成，总数量
            resultMap.put("pendingCount",
                    appTaskService.selectCountByTypeAndStatus1(taskType, Stream.of("1").collect(Collectors.toList()),
                            idList));
            resultMap.put("executingCount",
                    appTaskService.selectCountByTypeAndStatus1(taskType, Stream.of("2").collect(Collectors.toList()),
                            idList));
            resultMap.put("finishCount",
                    appTaskService.selectCountByTypeAndStatus1(taskType, Stream.of("3").collect(Collectors.toList()),
                            idList));
            resultMap.put("total", appTaskService.selectCountByTypeAndStatus1(taskType, null, idList));
            return DataReturn.ok(resultMap);
        }

        // 待执行,执行中，已完成，总数量
        resultMap.put("pendingCount",
                appTaskService.selectCountByTypeAndStatus(taskType, Stream.of("1").collect(Collectors.toList()),
                        userId));
        resultMap.put("executingCount",
                appTaskService.selectCountByTypeAndStatus(taskType, Stream.of("2").collect(Collectors.toList()),
                        userId));
        resultMap.put("finishCount",
                appTaskService.selectCountByTypeAndStatus(taskType, Stream.of("3").collect(Collectors.toList()),
                        userId));
        resultMap.put("total", appTaskService.selectCountByTypeAndStatus(taskType, null, userId));
        return DataReturn.ok(resultMap);
    }

    //查询人的任务数量
    @GetMapping(value = "/taskCount1", produces = "application/json;charset=UTF-8")
    @ApiOperation("查询人的任务数量")
    public DataReturn taskCount1(@RequestParam(required = false) Long userId) {
        Map<String, Integer> resultMap = new HashMap<>();
        // 待执行,执行中，已完成，总数量
        resultMap.put("pendingCount",
                appTaskService.selectCountByTypeAndStatus(null, Stream.of("1").collect(Collectors.toList()),
                        userId));
        resultMap.put("executingCount",
                appTaskService.selectCountByTypeAndStatus(null, Stream.of("2").collect(Collectors.toList()),
                        userId));
        resultMap.put("finishCount",
                appTaskService.selectCountByTypeAndStatus(null, Stream.of("3").collect(Collectors.toList()),
                        userId));
        resultMap.put("total", appTaskService.selectCountByTypeAndStatus(null, null, userId));
        return DataReturn.ok(resultMap);
    }


    @PostMapping(value = "/updateAppTaskByParam", produces = "application/json;charset=UTF-8")
    @ApiOperation("通过参数修改任务")
    public DataReturn updateAppTaskByParam(@RequestBody AppTask appTask) {
        try {
            appTaskService.updateAppTaskByParam(appTask);
            return DataReturn.ok();
        } catch (Exception e) {
            return DataReturn.failure(ResultCode.SERVER_ERROR, e.getMessage());
        }
    }
}
